package com.ww.springboot.boot.algorithm.leetcode1;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 描述：只出现一次的数字
 *
 * @author wanwei
 * @since 2021-10-30 14:52
 */
public class OneTimesNumTest {

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 5, 4, 3};
        System.out.println(Arrays.toString(singleNumber2(array)));
    }

    public static int[] singleNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();

        for (int i = 0; i < nums.length; i++) {
            if (!set.add(nums[i])) {
                set.remove(nums[i]);
            }
        }
        int[] array = new int[2];
        Object b[] = set.toArray();
        for (int i = 0; i < b.length; i++) {
            array[i] = (int) b[i];
        }
        return array;
    }

    public static int[] singleNumber2(int[] nums) {
        int val = 0, a = 1;
        int[] ans = new int[2];

        for (int item : nums) {
            val ^= item;
        }

        while ((val & a) == 0) a <<= 1;

        for (int item : nums) {
            if ((item & a) == 0) {
                ans[1] ^= item;
            }
        }

        ans[0] = val ^ ans[1];

        return ans;
    }
}
